package kt_test.util

object OxygenDataParser {
    fun extractSpo2FromFrame(data: ByteArray): Float? {
        val header = byteArrayOf(0x55.toByte(), 0xAA.toByte(), 0xAA.toByte(), 0x55.toByte())
        val footer = byteArrayOf(0xAB.toByte(), 0xFF.toByte(), 0x3E.toByte(), 0x2F.toByte())

        if (data.size >= 14 &&
            data.sliceArray(0..3).contentEquals(header) &&
            data[4] == 0x0E.toByte() &&
            data[5] == 0xEF.toByte() &&
            data.takeLast(4).toByteArray().contentEquals(footer)
        ) {
            val raw = data.sliceArray(6..9)
            val value = (raw[3].toInt() and 0xFF shl 24) or
                    (raw[2].toInt() and 0xFF shl 16) or
                    (raw[1].toInt() and 0xFF shl 8) or
                    (raw[0].toInt() and 0xFF)
            return value.toFloat()
        }
        return null
    }
}
